var bds = []; // 可连接设备列表
var deviceId = null,
	bconnect = false;
var bss = []; // 连接设备服务列表
var serviceId = null;
var bscs = []; // 连接设备服务对应的特征值列表
var characteristicId = null;
var bscws = []; // 可写特征值列表
var wcharacteristicId = null;
// 重设数据 
function resetDevices(d, s) {
	
}

function buffer2hex(value) {
	var t = '';
	if (value) {
		var v = new Uint8Array(value);
		for (var i in v) {
			t += '0x' + v[i].toString(16) + ' ';
		}
	} else {
		t = '无效值';
	}
	return t;
}

// 打开蓝牙 
function openBluetooth() {
	console.log('打开蓝牙适配器：');
	plus.bluetooth.openBluetoothAdapter({
		success: function(e) {
			console.log('打开成功!');
		},
		fail: function(e) {
			console.log('打开失败! ' + JSON.stringify(e));
		}
	});
}

// 开始搜索蓝牙设备 
function startDiscovery() {
	console.log('开始搜索蓝牙设备：');
	resetDevices();
	plus.bluetooth.startBluetoothDevicesDiscovery({
		success: function(e) {
			console.log('开始搜索成功!');
		},
		fail: function(e) {
			console.log('开始搜索失败! ' + JSON.stringify(e));
		}
	});
}

// 停止搜索蓝牙设备 
function stopDiscovery() {
	console.log('停止搜索蓝牙设备：');
	plus.bluetooth.stopBluetoothDevicesDiscovery({
		success: function(e) {
			console.log('停止搜索成功!');
		},
		fail: function(e) {
			console.log('停止搜索失败! ' + JSON.stringify(e));
		}
	});
}

// 选择蓝牙设备 
function selectDevice() {
	if (bds.length <= 0) {
		plus.nativeUI.toast('未搜索到有效蓝牙设备!');
		return;
	}
	var bts = [];
	for (var i in bds) {
		var t = bds[i].name;
		if (!t || t.length <= 0) {
			t = bds[i].deviceId;
		}
		bts.push({
			title: t
		});
	}
	plus.nativeUI.actionSheet({
		title: "选择蓝牙设备",
		cancel: "取消",
		buttons: bts
	}, function(e) {
		if (e.index > 0) {
			document.getElementById('deivce').value = bds[e.index - 1].name;
			deviceId = bds[e.index - 1].deviceId;
			console.log('选择了"' + bds[e.index - 1].name + '"');
		}
	});
}

// 连接蓝牙设备 
function connectDevice() {
	if (!deviceId) {
		plus.nativeUI.toast('未选择设备!');
		return;
	}
	console.log('连接设备: ' + deviceId);
	plus.bluetooth.createBLEConnection({
		deviceId: deviceId,
		success: function(e) {
			console.log('连接成功!');
		},
		fail: function(e) {
			console.log('连接失败! ' + JSON.stringify(e));
		}
	});
}

// 获取设备服务 
function getServices() {
	if (!deviceId) {
		plus.nativeUI.toast('未选择设备!');
		return;
	}
	if (!bconnect) {
		plus.nativeUI.toast('未连接蓝牙设备!');
		return;
	}
	resetDevices(true);
	console.log('获取蓝牙设备服务:');
	plus.bluetooth.getBLEDeviceServices({
		deviceId: deviceId,
		success: function(e) {
			var services = e.services;
			console.log('获取服务成功! ' + services.length);
			if (services.length > 0) {
				for (var i in services) {
					bss.push(services[i]);
					console.log(JSON.stringify(services[i]));
				}
				if (bss.length > 0) { // 默认选择最后一个服务
					document.getElementById('service').value = serviceId = bss[bss.length - 1].uuid;
				}
			} else {
				console.log('获取服务列表为空?');
			}
		},
		fail: function(e) {
			console.log('获取服务失败! ' + JSON.stringify(e));
		}
	});
}

// 选择服务 
function selectService() {
	if (bss.length <= 0) {
		plus.nativeUI.toast('未获取到有效蓝牙服务!');
		return;
	}
	var bts = [];
	for (var i in bss) {
		bts.push({
			title: bss[i].uuid
		});
	}
	plus.nativeUI.actionSheet({
		title: "选择服务",
		cancel: "取消",
		buttons: bts
	}, function(e) {
		if (e.index > 0) {
			document.getElementById('service').value = serviceId = bss[e.index - 1].uuid;
			console.log('选择了服务: "' + serviceId + '"');
		}
	});
}

// 获取服务的特征值 
function getCharacteristics() {
	if (!deviceId) {
		plus.nativeUI.toast('未选择设备!');
		return;
	}
	if (!bconnect) {
		plus.nativeUI.toast('未连接蓝牙设备!');
		return;
	}
	if (!serviceId) {
		plus.nativeUI.toast('未选择服务!');
		return;
	}
	resetDevices(true, true);
	console.log('获取蓝牙设备指定服务的特征值:');
	plus.bluetooth.getBLEDeviceCharacteristics({
		deviceId: deviceId,
		serviceId: serviceId,
		success: function(e) {
			var characteristics = e.characteristics;
			console.log('获取特征值成功! ' + characteristics.length);
			if (characteristics.length > 0) {
				for (var i in characteristics) {
					var characteristic = characteristics[i];
					console.log(JSON.stringify(characteristic));
					if (characteristic.properties) {
						if (characteristic.properties.read) {
							bscs.push(characteristics[i]);
						}
						if (characteristic.properties.write) {
							bscws.push(characteristics[i]);
							if (characteristic.properties.notify || characteristic.properties.indicate) {
								plus.bluetooth.notifyBLECharacteristicValueChange({ //监听数据变化
									deviceId: deviceId,
									serviceId: serviceId,
									characteristicId: characteristic.uuid,
									success: function(e) {
										console.log('notifyBLECharacteristicValueChange ' + characteristic.uuid + ' success.');
									},
									fail: function(e) {
										console.log('notifyBLECharacteristicValueChange ' + characteristic.uuid + ' failed! ' + JSON.stringify(e));
									}
								});
							}
						}
					}
				}
				if (bscs.length > 0) { // 默认选择最后特征值
					document.getElementById('characteristic').value = characteristicId = bscs[bscs.length - 1].uuid;
				}
				if (bscws.length > 0) { // 默认选择最后一个可写特征值
					document.getElementById('wcharacteristic').value = wcharacteristicId = bscws[bscws.length - 1].uuid;
				}
			} else {
				console.log('获取特征值列表为空?');
			}
		},
		fail: function(e) {
			console.log('获取特征值失败! ' + JSON.stringify(e));
		}
	});
}

// 选择特征值(读取) 
function selectCharacteristic() {
	if (bscs.length <= 0) {
		plus.nativeUI.toast('未获取到有效可读特征值!');
		return;
	}
	var bts = [];
	for (var i in bscs) {
		bts.push({
			title: bscs[i].uuid
		});
	}
	plus.nativeUI.actionSheet({
		title: '选择特征值',
		cancel: '取消',
		buttons: bts
	}, function(e) {
		if (e.index > 0) {
			document.getElementById('characteristic').value = characteristicId = bscs[e.index - 1].uuid;
			console.log('选择了特征值: "' + characteristicId + '"');
		}
	});
}

// 读取特征值数据 
function readValue() {
	if (!deviceId) {
		plus.nativeUI.toast('未选择设备!');
		return;
	}
	if (!bconnect) {
		plus.nativeUI.toast('未连接蓝牙设备!');
		return;
	}
	if (!serviceId) {
		plus.nativeUI.toast('未选择服务!');
		return;
	}
	if (!characteristicId) {
		plus.nativeUI.toast('未选择读取的特征值!');
		return;
	}
	console.log('读取蓝牙设备的特征值数据: ');
	plus.bluetooth.readBLECharacteristicValue({
		deviceId: deviceId,
		serviceId: serviceId,
		characteristicId: characteristicId,
		success: function(e) {
			console.log('读取数据成功!');
		},
		fail: function(e) {
			console.log('读取数据失败! ' + JSON.stringify(e));
		}
	});
}

// 选择特征值(写入) 
function selectwCharacteristic() {
	if (bscws.length <= 0) {
		plus.nativeUI.toast('未获取到有效可写特征值!');
		return;
	}
	var bts = [];
	for (var i in bscws) {
		bts.push({
			title: bscws[i].uuid
		});
	}
	plus.nativeUI.actionSheet({
		title: '选择特征值',
		cancel: '取消',
		buttons: bts
	}, function(e) {
		if (e.index > 0) {
			document.getElementById('wcharacteristic').value = wcharacteristicId = bscws[e.index - 1].uuid;
			console.log('选择了特征值: "' + wcharacteristicId + '"');
		}
	});
}

// 写入特征值数据 
function writeValue() {
	if (!deviceId) {
		plus.nativeUI.toast('未选择设备!');
		return;
	}
	if (!bconnect) {
		plus.nativeUI.toast('未连接蓝牙设备!');
		return;
	}
	if (!serviceId) {
		plus.nativeUI.toast('未选择服务!');
		return;
	}
	if (!wcharacteristicId) {
		plus.nativeUI.toast('未选择写入的特征值!');
		return;
	}
	var value = document.getElementById('writevalue').value;
	if (!value || value == '') {
		plus.nativeUI.toast('请输入需要写入的数据');
		document.getElementById('writevalue').focus();
		return;
	}
	//var ss = [84,69,88,84,32,187,185,203,175,190,245,188,198,203,227,187,250,200,253,188,182,201,207,191,219,191,219,201,250,191,236,201,250,191,236,191,188,202,212,44,117,110,100,101,102,105,110,101,100,44,34,117,110,100,101,102,105,110,101,100,34,44,48,44,117,110,100,101,102,105,110,101,100,44,117,110,100,101,102,105,110,101,100,44,34,117,110,100,101,102,105,110,101,100,34,13,10,80,82,73,78,84,32,49,44,49,13,10];
	var command = jpPrinter.createNew()
	command.setText(value);
	command.setPagePrint();
	var ss = command.getData();
	console.log(deviceId + "s1s" + serviceId + 's2s' + wcharacteristicId + 'ss' + ss);
	var uint8Buf = Array.from(ss);

	function split_array(datas, size) {
		var result = {};
		var j = 0
		for (var i = 0; i < datas.length; i += size) {
			result[j] = datas.slice(i, i + size)
			j++
		}
		console.log(result)
		return result
	}
	var sendloop = split_array(uint8Buf, 20);
	// console.log(sendloop.length)
	function realWriteData(sendloop, i) {
		var data = sendloop[i]
		if (typeof(data) == "undefined") {
			return
		}
		console.log("第【" + i + "】次写数据" + data)
		var buffer = new ArrayBuffer(data.length)
		var dataView = new DataView(buffer)
		for (var j = 0; j < data.length; j++) {
			dataView.setUint8(j, data[j]);
		}
		plus.bluetooth.writeBLECharacteristicValue({
			deviceId: deviceId,
			serviceId: serviceId,
			characteristicId: wcharacteristicId,
			value: buffer,
			success: function(res) {
				//realWriteData(sendloop, i + 1);
				setTimeout(function() {
					realWriteData(sendloop, i + 1);
				}, 100);
			}
		})
	}
	var i = 0;
	realWriteData(sendloop, i);
	// 转换为ArrayBuffer写入蓝牙
	// str2ArrayBuffer(value, function(buffer) {
	// 	console.log('写入蓝牙设备的特征值数据: ');
	// 	plus.bluetooth.writeBLECharacteristicValue({
	// 		deviceId: deviceId,
	// 		serviceId: serviceId,
	// 		characteristicId: wcharacteristicId,
	// 		value: buffer,
	// 		success: function(e) {
	// 			console.log('写入数据成功!');
	// 		},
	// 		fail: function(e) {
	// 			console.log('写入数据失败! ' + JSON.stringify(e));
	// 		}
	// 	});
	// });
}

function str2ArrayBuffer(s, f) {
	var b = new Blob([s], {
		type: 'text/plain'
	});
	var r = new FileReader();
	r.readAsArrayBuffer(b);
	r.onload = function() {
		if (f) f.call(null, r.result)
	}
}


// 断开蓝牙设备
function disconnectDevice() {
	if (!deviceId) {
		plus.nativeUI.toast('未选择设备!');
		return;
	}
	resetDevices(true);
	console.log('断开蓝牙设备连接：');
	plus.bluetooth.closeBLEConnection({
		deviceId: deviceId,
		success: function(e) {
			console.log('断开连接成功!');
		},
		fail: function(e) {
			console.log('断开连接失败! ' + JSON.stringify(e));
		}
	});
}

// 关闭蓝牙
function closeBluetooth() {
	console.log('关闭蓝牙适配器：');
	resetDevices();
	plus.bluetooth.closeBluetoothAdapter({
		success: function(e) {
			console.log('关闭成功!');
			bconnect = false;
		},
		fail: function(e) {
			console.log('关闭失败! ' + JSON.stringify(e));
		}
	});
}

// 关闭蓝牙
function onBluetoothDeviceFound() {
	console.log('监控蓝牙：');
	resetDevices();
	plus.bluetooth.onBluetoothDeviceFound(function(devices) {
		// /console.log('--------------new-----------------------' + JSON.stringify(devices))
		var re = JSON.parse(JSON.stringify(devices))
		console.log(re.devices[0].name + "  " + re.devices[0].deviceId)
		var name = re.devices[0].name
		if (name != "") {
			//console.log(re.devices[0].name+'----'+that.printer+ that.printer+'----------new-----------------------'+JSON.stringify(devices))
			if (re.devices[0].deviceId == self.printer) {
				console.log('--------------new-----------------------' + JSON.stringify(devices))
				self.onConn(re.devices[0]);
				self.stopFindBule();
			}
		}
	});
}
